
//进入页面后使用ajax请求用户数据
var users = [];
$.ajax({
    url: "/query",
    method: "get",
    data:{
        dir:"1"
    },
    success: function (xhr) {
        users = xhr;
        // console.log(users);
    }
});

//使用ajax提交注册信息
$(".confirm_reg").click(function () {
    if (uname_code == 1 && pwd_code == 1 && pwd_code1 == 1) {
        $.ajax({
            url: "/register",
            method: "post",
            data: {
                uname: $("#uname_reg").val(),
                pwd: $("#pwd_reg").val()
            },
            success: function (xhr) {
                // console.log(xhr);
                if (xhr == '0') {
                    $("#uname_reg").parent().siblings("p").html("该用户名使用的人太多了，请更换一下").removeClass("text-success").addClass("text-danger");
                } else if (xhr) {
                    swal('注册成功');
                } else {
                    swal('服务器出现未知错误');
                }
            }
        });
    } else if (uname_code == 0 && pwd_code == 0 && pwd_code1 == 0) {
        swal('请输入用户名和密码后再提交');
        return false;
    } else {
        swal('用户名和密码有误，请按照提示修改后提交');
        return false;
    }
    return false;
});
$("button[data-target='#login']").click(function () {
    swal('您已登录，请勿重复登录');
    return false;
});

//使用ajax请求来发布微博
$(".weibo_publish").click(function () {
    if ($(".weibo_con").val().trim() == '') {
        swal('发布内容不能为空');
    } else {
        var uname = $(".username_title").html();
        var pic = query(uname);
        console.log(pic);
        var time = new Date();
        time = formatDate(time);
        $.ajax({
            url: "/publish",
            method: "get",
            data: {
                username: uname,
                pic: pic,
                content: $(".weibo_con").val(),
                date: time,
                like: 0,
                comment: []
            },
            success: function (xhr) {
                // console.log(12);
                if (xhr) {
                    var $con =
                        $(`<div class="container weibo_message" index="${xhr._id.toString()}">
                            <div class="row col-sm-8 col-sm-offset-2">
                                <div class="panel panel-primary">
                                    <div class="panel-body">
                                        <h4>
                                            <img src="${xhr.pic}" alt="">
                                            <i class="username">${xhr.username}</i>
                                            <button type="button" class="close delete_ele" aria-hidden="true">&times;</button>
                                        </h4>
                                        <div class="blogcon">${xhr.content}</div>
                                        <div class="comments">
                                            
                                        </div>
                                    </div>
                                    <div class="panel-footer clearfix">
                                        <div class="function">
                                            <span class="date text-success">${xhr.date}</span>
                                            <i class="like text-danger glyphicon glyphicon-thumbs-up" index="0">
                                                <span class="num">${xhr.like}</span>
                                            </i>
                                            <a href="#" class="text-warning remark" click="0">评论</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>`);
                    $(".weibo").append($con);
                    $(".weibo_con").val("");
                    swal('发布信息成功');
                    $(window).scrollTop($con.offset().top);

                } else {
                    swal('服务器端发生未知错误');
                }
            }
        });
    }
    return false;
});
//点击评论按钮打开对应的输入框
$(".weibo").on('click', '.remark', function () {
    if ($(this).attr("click") == "1") {
        $(this).parent().siblings(".form-inline").remove();
        $(this).attr("click", "0");
        return false;
    }
    $(this).parent().after(`<form class="form-inline">
    <div class="form-group">
      <input type="text" class="form-control reply" placeholder="输入要发表的评论">
    </div>
    <button type="submit" class="btn btn-success reply_confirm">确认发送</button>
  </form>`);
    //防止用户重复点击评论按钮
    $(this).attr("click", "1");
    var res = $(this);
    //为发送评论按钮绑定点击事件  发送ajax请求到后台
    $(".reply_confirm").click(function () {
        var msg = $(this).siblings(".form-group").children(".reply").val();
        if (msg.trim() == '') {
            swal('评论内容不能为空');
            return false;
        }
        var username = $(".username_title").html();
        var time = new Date();
        var date = formatDate(time);
        var index = $(this).parents(".weibo_message").attr("index");
        var that = $(this);
        // console.log(index);
        $.ajax({
            url: "/remark",
            method: "get",
            data: {
                username: username,
                msg: msg,
                date: date,
                id: index
            },
            success: function (xhr) {
                if (xhr) {//后台更新评论，返回指令局部更新评论信息
                    var $con = $(`
                    <div class="comments_con">
                        <i class="username_title">${username}</i>&nbsp;回复：
                        <span class="replyMessage">${msg}</span>
                        <span class="date_reply text-success">&nbsp;&nbsp;&nbsp;&nbsp;${date}</span>
                    </div>
                    `);
                    that.parents(".weibo_message").find(".comments").append($con);//添加评论信息
                    res.parent().siblings(".form-inline").remove();//删除发送评论输入框
                    res.attr("click", "0");//将评论按钮重置为可点击状态

                } else {
                    swal('服务器端发生了未知错误');
                }
            }
        });
        return false;
    });
    return false;
});
//使用ajax请求删除已经发布的博客
$(".weibo").on('click', '.delete_ele', function () {
    var user = $(".username_title").html();
    if (user == $(this).siblings(".username").html()) {//当前用户与微博发布者是同一人时，才可以删除微博
        var index = $(this).parents(".weibo_message").attr('index');//获取当前微博的id
        var that = $(this);
        $.ajax({
            url: "/others",
            method: "get",
            data: {
                dir: "0",
                id: index
            },
            success: function (xhr) {
                if (xhr) {//删除成功xhr为true
                    that.parents(".weibo_message").remove();
                    swal('删除完成');
                } else {
                    swal('服务器端发生了未知错误');
                }
            }
        });
    } else {
        swal('该信息不是您发布的，您无权这样做');
    }
    return false;
});
//使用ajax请求完成点赞功能
$(".weibo").on("click",".function .like",function(){//weibo中当前的和未来生成的评论中的点赞都会绑定事件
    var num = parseInt($(this).children(".num").html());//获得当前点赞数量
    var index = $(this).parents(".weibo_message").attr('index');//获取当前微博的id
    var that = $(this);
    if($(this).attr("index") == "0"){//状态为"0"说明当前用户没有点赞
        $(this).attr("index","1");//切换为已点赞
        num++;
        
    }else{
        $(this).attr("index","0");//切换为未点赞
        num--;
    }
    //发送ajax请求后台更改点赞数量
    $.ajax({
        url: "/others",
        method: "get",
        data: {
            dir: "1",
            id: index,
            like:num
        },
        success:function(xhr){
            if(xhr){
                that.children(".num").html(num);
            }else{
                swal('服务器端发生了未知错误');
            }
        }
    });
    

});
//注销用户

$(".del_user").click(function(){
    SimplePop.confirm("确认注销您的账号吗？",{

        type: "info",
    
        cancel: function(){
            
            return false;
        },
    
        confirm: function(){
            $.ajax({
                url:"/remove",
                method:"get",
                data:{
                    uname:$(".username_title").html()
                },
                success:function(xhr){
                    if(xhr){
                        swal('用户已注销');
                    setTimeout(function(){
                        location.href = "/";
                    },3000);
                    }
                }
            });
    
        }
    
    });
});




function query(uname) {
    var pic;
    users.forEach(ele => {
        if (ele.username == uname) {
            pic = ele.pic;
        }
    });
    return pic;
}

function formatDate(date) {
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日  ${date.getHours()}时${date.getMinutes()}分${date.getSeconds()}秒`;
}




